package microphone;

import java.io.ByteArrayInputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;

public class AudioThread extends Thread {

    private boolean running = true;
    public ServerThread serverThread;
    private AudioFormat format;

    public AudioThread(ServerThread sThread, AudioFormat format) {
        serverThread = sThread;
        this.format = format;
    }

    @Override
    public void run() {
        try {
            SourceDataLine line = AudioSystem.getSourceDataLine(format);
            line.open();
            line.start();
            running = true;
            while (running) {
                try {
                    byte[] audio = serverThread.soundQueue.take();
                    ByteArrayInputStream stream = new ByteArrayInputStream(audio);

                    int totalToRead = audio.length;
                    int total = 0;
                    int numBytesToRead = line.getBufferSize();

                    byte[] buffer = new byte[numBytesToRead];
                    while (total < totalToRead) {
                        int numBytesRead = stream.read(buffer, 0, numBytesToRead);
                        if (numBytesRead == -1) {
                            break;
                        }
                        total += numBytesRead;
                        line.write(buffer, 0, numBytesRead);
                    }
                } catch (InterruptedException ex) {
                    System.err.println(ex);
                }
            }
            line.close();
        } catch (LineUnavailableException ex) {
            System.err.println(ex);
        }
    }

    public void stopRunning() {
        running = false;
    }
}
